// pages/goods/goods.js
var http = require("../../utils/http.js");
Page({
  data: {
    categoryList: [{
      "merchantGoodsList": []
    }],
    distance:'',
    merchant:'',
    reduction:[],
    merchantName:'',
    merchantId: '',
    toView: '0',
    scrollTop: 100,
    foodCounts: 0,
    totalPrice: 0, // 总价格
    totalCount: 0, // 总商品数
    carArray: [],
    clearCart: [],
    minPrice: 10, //起送價格
    payDesc: '',
    deliveryPrice: 4, //配送費
    fold: true,
    selectFoods: [{
      price: 20,
      count: 2
    }],
    cartShow: 'none',
    status: 0,
    cartList: [],
    cartCountList: [{
      goodsId: '',
      counts: 0
    }],
    merchantBasket: {}
  },
  selectMenu: function (e) {
    var index = e.currentTarget.dataset.itemIndex;
    //console.log(e);
    this.setData({
      toView: 'order' + index.toString()
    })
    //console.log(this.data.toView);
  },
  //移除商品
  decreaseCart: function (e) {
    var index = e.currentTarget.dataset.itemIndex;
    var parentIndex = e.currentTarget.dataset.parentindex;
    if (this.data.categoryList[parentIndex].merchantGoodsList[index].cartCount == 0) {
      return;
    }
    this.data.categoryList[parentIndex].merchantGoodsList[index].inventory++;
    this.data.categoryList[parentIndex].merchantGoodsList[index].cartCount--;
    var num = this.data.categoryList[parentIndex].merchantGoodsList[index].cartCount;
    //console.log("---------------------");
   // console.log(this.data.categoryList[parentIndex].merchantGoodsList[index]);
    var mark = 'a' + index + 'b' + parentIndex
    var price = this.data.categoryList[parentIndex].merchantGoodsList[index].goodsSalePrice;
    var name = this.data.categoryList[parentIndex].merchantGoodsList[index].goodsName;
    var obj = {
      price: price,
      num: num,
      mark: mark,
      name: name,
      index: index,
      parentIndex: parentIndex
    };
    var carArray1 = this.data.carArray.filter(item => item.mark != mark);
    carArray1.push(obj);
    // console.log(carArray1);
    this.setData({
      carArray: carArray1,
      categoryList: this.data.categoryList
    })
    this.calTotalPrice()
    this.setData({
      payDesc: this.payDesc(),
    })
    //关闭弹起
    var count1 = 0
    for (let i = 0; i < carArray1.length; i++) {
      if (carArray1[i].num == 0) {
        count1++;
      }
    }
    //console.log(count1)
    if (count1 == carArray1.length) {
      if (num == 0) {
        this.setData({
          cartShow: 'none'
        })
      }
    }
    var params = {
      url: "/merchant/basket/addGoodsToCart",
      method: "POST",
      data: this.data.categoryList[parentIndex].merchantGoodsList[index],
      callBack: function (res) {
       // console.log(res);
      }
    };
    http.request(params);
  },
  decreaseShopCart: function (e) {
    //console.log('1');
    this.decreaseCart(e);
  },
  //添加到购物车
  addCart(e) {
    var index = e.currentTarget.dataset.itemIndex;
    var parentIndex = e.currentTarget.dataset.parentindex;
    if (this.data.categoryList[parentIndex].merchantGoodsList[index].inventory == 0) {
      return;
    }
    var inventory = this.data.categoryList[parentIndex].merchantGoodsList[index].inventory--;
    this.data.categoryList[parentIndex].merchantGoodsList[index].cartCount++;
    var num = this.data.categoryList[parentIndex].merchantGoodsList[index].cartCount;
    var mark = 'a' + index + 'b' + parentIndex
    var price = this.data.categoryList[parentIndex].merchantGoodsList[index].goodsSalePrice;
    var name = this.data.categoryList[parentIndex].merchantGoodsList[index].goodsName;

    //console.log(this.data.categoryList[parentIndex].merchantGoodsList[index]);
    var obj = {
      price: price,
      num: num,
      mark: mark,
      name: name,
      index: index,
      parentIndex: parentIndex
    };
    var carArray1 = this.data.carArray.filter(item => item.mark != mark)
    carArray1.push(obj)
    // console.log(carArray1);
    this.setData({
      carArray: carArray1,
      categoryList: this.data.categoryList
    })
    this.calTotalPrice();
    this.setData({
      payDesc: this.payDesc()
    });
    //添加商品到购物车
    var ths = this;
    var params = {
      url: "/merchant/basket/addGoodsToCart",
      method: "POST",
      data: this.data.categoryList[parentIndex].merchantGoodsList[index],
      callBack: function (res) {
        //console.log(res.content)
        ths.setData({
          merchantBasket: res.content
        })
        //将下标赋值给传过来的对象
        ths.data.merchantBasket.parentIndex = parentIndex;
        ths.data.merchantBasket.indexs = index;
        //添加商品后插入商品的下标
        var params3 = {
          url: "/merchant/basket/updateGoodsIndex",
          method: "POST",
          data: ths.data.merchantBasket,
          callBack: function (res) {}
        };
        http.request(params3);
      }
    };
    http.request(params);
  },
  addShopCart: function (e) {
    //console.log(123123)
    this.addCart(e);
  },
  //计算总价
  calTotalPrice: function () {
    var carArray = this.data.carArray;
    var totalPrice = 0;
    var totalCount = 0;
    for (var i = 0; i < carArray.length; i++) {
      totalPrice += carArray[i].price * carArray[i].num;
      totalCount += carArray[i].num
    }
    this.setData({
      totalPrice: totalPrice,
      totalCount: totalCount,
    });
  },
  //差几元起送
  payDesc() {
    if (this.data.totalPrice === 0) {
      let mini=this.data.miniPrice
      this.setData({
        minPrice:mini
      })
      return `￥${this.data.minPrice}元起送`;
    } else if (this.data.totalPrice < this.data.minPrice) {
      let diff = this.data.minPrice - this.data.totalPrice;
      return '还差' + diff + '元起送';
    } else {
      return '去结算';
    }
  },
  //結算
  pay() {
    if (this.data.totalPrice < this.data.minPrice) {
      return;
    }
    // window.alert('支付' + this.totalPrice + '元');
    //确认支付逻辑
    // var resultType = "success";
    // wx.redirectTo({
    //   url: '../goods/pay/pay?resultType=' + resultType
    // })
  },
  //彈起購物車
  toggleList: function () {
    if (!this.data.totalCount) {
      return;
    }
    this.setData({
      fold: !this.data.fold,
    })
    var fold = this.data.fold
    //console.log(this.data.fold);
    this.cartShow(fold)
  },
  cartShow: function (fold) {
    //console.log(fold);
    if (fold == false) {
      this.setData({
        cartShow: 'block',
      })
    } else {
      this.setData({
        cartShow: 'none',
      })
    }
   // console.log(this.data.cartShow);
  },
  tabChange: function (e) {
    var showtype = e.target.dataset.type;
    this.setData({
      status: showtype,
    });
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    //加载分类列表
    this.setData({
      merchantId: options.merchantId,
      distance:options.distance
    });
    this.getMerchant(this.data.merchantId);
    var ths = this;
    //加载分类列表
    var params = {
      url: "/merchant/category/getByMerchantId",
      method: "GET",
      data: {
        id: ths.data.merchantId
      },
      callBack: function (res) {
        ths.setData({
          categoryList: res.content
        });
        //console.log("11111111")
        //console.log(ths.data.categoryList)

        //加载购物车信息
        //console.log("22222222")
        //console.log(ths.data.categoryList)
        //var ths = this;
        var params2 = {
          url: "/merchant/basket/getCartListByUserId",
          method: "GET",
          data: {
            merchantId:ths.data.merchantId
          },
          callBack: function (res) {
            if (res.content == null) {
              return;
            }
            var totalP = 0;
            var totalN = 0;
           // console.log(res.content)
           // console.log(ths.data.categoryList)
            res.content.forEach(item => {
              ths.data.categoryList.forEach(item2 => {
                item2.merchantGoodsList.forEach(item3 => {
                  if (item.goodsId == item3.id) {
                    item3.cartCount = item.goodsNum;
                    item3.inventory = item3.inventory - item.goodsNum;
                  }
                })
              });
              var index = item.indexs;
              var parentIndex = item.parentIndex;
              var mark = 'a' + index + 'b' + parentIndex;
              var obj = {
                mark: mark,
                price: item.unitPrice,
                num: item.goodsNum,
                name: item.goodsName,
                index: item.indexs,
                parentIndex: item.parentIndex
              };
              totalP = item.unitPrice * item.goodsNum + totalP;
              totalN = totalN + item.goodsNum;
              ths.data.cartList.push(obj);
              ths.setData({
                totalPrice: totalP,
                totalCount: totalN,
                carArray: ths.data.cartList,
              })
              ths.setData({
                payDesc: ths.payDesc()
              });
            })
           // console.log("33333333333333")
           // console.log(ths.data.categoryList)
            ths.setData({
              categoryList: ths.data.categoryList
            })
            //console.log(ths.data.categoryList);

            // console.log(ths.data.carArray);
            // console.log(ths.data.totalPrice);
            // console.log(ths.data.totalCount);
          }
        };
        http.request(params2);

      }
    };
    http.request(params);
    //this.getIndexImgs();//记载轮播图
    //加载活动列表
    this.showActive();


  },
  getMerchant(id){
    let ths=this;
    var params = {
      url: "/platform/merchant/getMerchantById",
      method: "GET",
      data:{
          id:id
      },
      callBack: function (res) {
        ths.setData({
          merchant: res.content,
          miniPrice:res.content.merchantReachPrice
        });
        ths.setData({
          payDesc: ths.payDesc()
        })
      }
    };
    http.request(params);
  },
  //加载满减活动列表
  showActive(){
    let ths=this;
    var params = {
      url: "/merchant/getReductionByMerchantId",
      method: "GET",
      data:{
          id:ths.data.merchantId
      },
      callBack: function (res) {
        ths.setData({
          reduction: res.content,
        });
      }
    };
    http.request(params);
  },
  onReady: function () {
    // 页面渲染完成

  },
  onShow: function () {
    // 页面显示
    this.cartShow(true);
    this.toggleList();
    this.setData({
      
    })
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  empty() {
    this.data.categoryList.forEach(element => {
      element.merchantGoodsList.forEach(elementson => {
        elementson.inventory = elementson.inventory + elementson.cartCount;
        elementson.cartCount = 0;
      })
    });
    this.setData({
      totalPrice: 0
    })
    this.setData({
      categoryList: this.data.categoryList,
      carArray: this.data.clearCart,
      totalCount: 0,
      payDesc: this.payDesc()
    })
    this.cartShow(true);
  },
  addOrder(){
    let ths=this
    if(this.data.totalPrice<this.data.minPrice){
      return;
    }
    //下订单逻辑
    // var params = {
    //   url: "/user/placeOrder",
    //   method: "get",
    //   data:{
    //     merchantId:ths.data.merchantId
    //   },
    //   callBack: function (res) {
    //     if(res.content){
          wx.navigateTo({
            url: '/pages/submit-order/submit-order?merchantId='+this.data.merchantId+'&distance='+this.data.distance,
          })
      //   }
      // }
    // };
    // http.request(params);
  }
})